package com.ruoyi.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.map.MapUtil;
import com.ruoyi.cms.domain.Category;
import com.ruoyi.cms.exception.CmsException;
import com.ruoyi.cms.mapper.CategoryMapper;
import com.ruoyi.cms.service.CategoryService;
import com.ruoyi.common.utils.TreeBuildUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *      栏目管理业务类
 * @author LIGW
 *
 */
@Service
public class CategoryServiceImpl implements CategoryService {
	@Autowired
	private CategoryMapper categoryMapper;

	/**
	 * 添加
	 */
	@Override
	public void save(Category category) {
		try {
			categoryMapper.insert(category);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 *  列表
	 */
	@Override
	public List<Category> queryListByPage(Map<String,Object> params) {
		List<Category> list = categoryMapper.queryList();
		if (CollectionUtils.isNotEmpty(list)){
			list.forEach(i->{
                Map<String,Object> newEntity = MapUtil.builder(params).build();
                newEntity.put("parentId", i.getId());
                List<Category> childrenNodes = getTreeList(newEntity);
                i.setChildren(childrenNodes);
				//List<Category> childrenNodes = categoryMapper.selectByParentId(i.getId());
				i.setChildrenFlag(CollectionUtils.isEmpty(childrenNodes)?0:1);
			});
		}

		return list;
	}

    @Override
    public List< Category > getAllList() {
        return categoryMapper.queryAll();
    }

    /**
	 *  编辑回显
	 */
	@Override
	public Category selectById(String id) {
		return categoryMapper.selectById(id);
	}

	/**
	 * 查看子栏目
	 */
	@Override
	public List<Category> selectByParentId(String id) {
		List<Category> list = categoryMapper.selectByParentId(id);
		if (CollectionUtils.isNotEmpty(list)){
			list.forEach(i->{
				List<Category> childrenNodes = categoryMapper.selectByParentId(i.getId());
				i.setChildrenFlag(CollectionUtils.isEmpty(childrenNodes)?0:1);
			});
		}
		return list;
	}

	/**
	 * 修改
	 */
	@Override
	public int update(Category category) {
		return categoryMapper.updateById(category);
	}

	/**
	 * 删除
	 * @throws CmsException
	 */
	@Override
	@Transactional
	public int delete(String id) throws CmsException {
		List<Category> list = categoryMapper.selectByParentId(id);
		Category category = categoryMapper.selectById(id);
		return cascadeDelete(category);
	}

	@Override
	public Category queryCategoryByCode(String code) {
		return this.categoryMapper.queryCategoryByCode(code);
	}

	@Override
	public void updateSort(List<Category> list) {
		for(int i = 0;i < list.size();i++) {
			Category category = new Category();
			category.setId(list.get(i).getId());
			category.setSort(list.get(i).getSort());
			this.categoryMapper.updateById(category);
		}
	}

	@Override
	public List<Category> getTreeList(Map<String,Object> params) {
		List<Category> list = categoryMapper.queryListByParams(params);
		if(list != null && list.size()>0) {
			for(int i= 0;i < list.size();i++) {
				Category category = list.get(i);
				Map<String,Object> newEntity = MapUtil.builder(params).build();
				newEntity.put("parentId", category.getId());
                List<Category> cg = getTreeList(newEntity);
				category.setChildren(cg);
                category.setChildrenFlag(CollectionUtils.isEmpty(cg)?0:1);
			}
		}
		return list;
	}

    @Override
    public List<Category> getTreeList() {
        return getTreeList(new HashMap<String,Object>());
    }

	@Override
	public List<Category> queryListByCode(Map<String, Object> entity) {
		return categoryMapper.queryListByParams(entity);
	}

	@Override
	public List<Category> queryAll() {
		return categoryMapper.queryAll();
	}

    @Override
    public List<Tree<String>> buildMenuTreeSelect(List<Category> categories) {
        if (CollUtil.isEmpty(categories)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(categories, (category, tree) ->
            tree.setId(category.getId())
                .setParentId(category.getParentId())
                .setName(category.getCnname())
                .setWeight(category.getSort()));
    }

    /**
	 * 级联删除栏目
	 * @param category
	 * @return
	 */
	private int cascadeDelete(Category category) {
		int counter = 0;
		if(category == null) {
			return counter;
		}
		List<Category> categorys = categoryMapper.selectByParentId(category.getId());
		for(Category temp : categorys) {
			counter += cascadeDelete(temp);
		}
		counter += categoryMapper.deleteById(category.getId());
		return counter;
	}

}
